import {
  WXLOGIN, AUTHORIZED, GETCOOKIE
} from './mutation-types.js'
import axios from 'axios'
// IS_LOGIN
export default {
  // 是否登录
  // [IS_LOGIN](state,bool){
  //   state.isLogin = bool
  // }WXLOGIN
  [WXLOGIN] (state, wxParams) {
    console.log(wxParams)
    console.log(state.transferUrl)
    // id-路由+secondPath+二级目录
    axios.get('//prem2.yaolaivip.com/api/wechat/code', {
      params: {
        redirect_uri: state.transferUrl,
        isSilence: true,
        state: '-' + wxParams.url + '+secondPath+reception'
      }
    }).then((response) => {
      if (response.data.code === 9999) {
        // alert(response.data.data)
        window.location.href = response.data.data
      }
    })
    .catch((error) => {
      console.log(error)
    })
  },
  // 获取cookie
  [GETCOOKIE] (state, key) {
  //  cookie取出来的格式：'key1=value1; key2=value2; key3=value3'
    // return localStorage.getItem(key)?localStorage.getItem(key):null
    if (localStorage.getItem(key)) {
      return localStorage.getItem(key)
    } else {
      // 查找一个值，可以把它转换为数组，通过循环、对比来查找
      var arr = document.cookie.split('; ')// 不要忘记空格!!!
      if (arr.length > 0) {
        for (var i = 0; i < arr.length; i++) {
          if (arr[i].indexOf('ylUserInfo=') !== -1) {
            if (arr[i] !== 'ylUserInfo=' || arr[i] !== 'ylUserInfo=;') {
              return arr[i].replace('ylUserInfo=', '')
            }
          }
        }
      } else {
        return null// 没有找到该cookie，返回null
      }
    }
  },
  // 微信授权
  [AUTHORIZED] (state, wxObj) {
    console.log(wxObj)
    console.log(state.transferUrl)
    // alert('不带code参数的普通 链接,接下来获取code，重定向带code的参数'+state.redirectUri+wxObj.url)
    // 1.get请求,获取code
    axios.get('//prem2.yaolaivip.com/api/wechat/code', {
      params: {
        redirect_uri: state.transferUrl,
        isSilence: true,
        state: wxObj.fullPath
      }
    })
    .then(function (response) {
      // alert('重定向:'+response.data.data)
      if (response.data.code === 9999) {
        // window.location.href = response.data.data
      }
    })
    .catch((error) => {
      console.log(error)
    })
  }
}
